package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @Author：cxl
 * @Package：com.itheima.filter
 * @Project：web-project
 * @name：TokenFilter
 * @Date：2025-09-30 3:16 pm
 * @Filename：TokenFilter
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //login请求放行，其他请求校验token有效性
        //获取请求路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String path = request.getRequestURI();
        log.info("请求路径{}", path);
        if (path.endsWith("/login")) {
            //只有以/login才放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //不是登录请求就校验token有效性
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            log.info("\nFilter验证token是否合法");
            try {
                Claims claims = JwtUtils.parseJWT(token);
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            } catch (Exception e) {
                log.error("解析token失败", e);
            }finally {
                CurrentHolder.remove();
            }
        }
        //没有token或者失败的处理
        //设置状态码为401，客户端没有登录，权限是403
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    }
}
